package com.junlong0716.enjoylearning.ui

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import com.afollestad.materialdialogs.MaterialDialog
import com.blankj.utilcode.util.ToastUtils
import com.junlong0716.enjoylearning.MyApp
import com.junlong0716.enjoylearning.R
import com.junlong0716.enjoylearning.adapter.CollectionAdapter
import com.junlong0716.enjoylearning.constant.NetConstant
import com.junlong0716.enjoylearning.entity.AudioEntity
import com.junlong0716.enjoylearning.entity.CollectionEntity
import com.junlong0716.enjoylearning.net.api.NetApi
import com.junlong0716.enjoylearning.service.MusicService
import com.junlong0716.enjoylearning.service.PlayerManager
import com.junlong0716.enjoylearning.widget.PlayerBarView
import com.junlong0716.getknowledgedemo.decoration.DividerItemDecoration
import com.junlong0716.module.common.rxbus.RxBus
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_study_collection.*
import kotlinx.android.synthetic.main.view_title_bar.*
import org.json.JSONObject

class StudyCollectionActivity : AppCompatActivity(), View.OnClickListener {
    private lateinit var studyCollectionAdapter: CollectionAdapter
    private lateinit var data: ArrayList<CollectionEntity>

    private var mPlayerBarView: PlayerBarView? = null
    private var musicService: MusicService? = null
    private var mPlayerManager: PlayerManager? = null

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.rl_back -> {
                finish()
            }
            else -> {
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_study_collection)
        RxBus.getDefault().register(this)
        bindMyService()
        rl_back.setOnClickListener(this)
        tv_title.text = "我的收藏"
        data = ArrayList()
        requestCollectionList()
        studyCollectionAdapter = CollectionAdapter(data)
        rv_collection.layoutManager = LinearLayoutManager(this)
        rv_collection.adapter = studyCollectionAdapter
        setOnRecyclerViewScrollDirectListener(rv_collection)
        //studyHistoryAdapter.emptyView = LayoutInflater.from(this).inflate(R.layout.view_empty, null)
        srl_refresh.isEnableLoadMore = false
        rv_collection.addItemDecoration(DividerItemDecoration(this, LinearLayoutManager.VERTICAL, 4, ContextCompat.getColor(this, R.color.recyclerview_divider_gray)))


        studyCollectionAdapter.setOnItemClickListener { adapter, view, position ->
            when (data[position].knowledgeType) {
                1 -> {
                    val intent = Intent()
                    intent.setClass(this, VideoActivity::class.java)
                    intent.putExtra("video_url", NetConstant.REQUEST_SOURCE + data[position].fileAddress)
                    intent.putExtra("video_id", data[position].knowledgeId)
                    //intent.putExtra("video_author", data[position].)
                    startActivity(intent)
                }
                2 -> {
                    val audioEntity = AudioEntity(data[position].id, NetConstant.REQUEST_SOURCE + data[position].fileAddress, data[position].knowledgeTitle!!, NetConstant.REQUEST_SOURCE + data[position].coverImg)
                    mPlayerManager!!.playMusic(audioEntity)
                }
                3 -> {
                    val intent = Intent()
                    intent.setClass(this, WebActivity::class.java)
                    intent.putExtra("document_url", NetConstant.REQUEST_SOURCE + data[position].fileAddress)
                    intent.putExtra("document_title", data[position].knowledgeTitle)
                    intent.putExtra("document_id", data[position].id)
                    startActivity(intent)
                }
                else -> {

                }
            }
        }

        studyCollectionAdapter.setOnItemLongClickListener { adapter, view, position ->

            MaterialDialog.Builder(this)
                    .title("是否删除？")
                    .canceledOnTouchOutside(false)
                    .positiveText("是")
                    .negativeText("否")
                    .onPositive { dialog, which ->
                        requestDelMyCollect(position)
                    }
                    .onNegative { dialog, which ->
                        dialog.dismiss()
                    }
                    .show()
            return@setOnItemLongClickListener true
        }
    }
    private var conn = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {

        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val myBinder = service as (MusicService.MyBinder)
            musicService = myBinder.getService()
            mPlayerManager = musicService!!.getPlayerManager()
            mPlayerBarView = PlayerBarView(this@StudyCollectionActivity, mPlayerManager!!, rl_container)
        }
    }

    private fun bindMyService() {
        val intent = Intent(this, MusicService::class.java)
        bindService(intent, conn, AppCompatActivity.BIND_AUTO_CREATE)
    }

    private fun requestDelMyCollect(position: Int) {
        val map = HashMap<String, Any>()
        map["id"] = data[position].id
        val jsonObject = JSONObject(map)
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_KNOWLEDGE_DEL_COLLECT)
                .tag(this)
                .upJson(jsonObject)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val jsonObj = JSONObject(response!!.body())
                        if (jsonObj.getString("code") == "200") {
                            ToastUtils.showShort("删除成功！")
                            requestCollectionList()
                        }
                    }
                })


    }

    private fun requestCollectionList() {
        val map = HashMap<String, Any>()
        map["userId"] = MyApp.instance().userAccount!!.id
        val jsonObject = JSONObject(map)
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_KNOWLEDGE_QUERY_COLLECT)
                .tag(this)
                .upJson(jsonObject)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        //Logger.json(response!!.body())

                        val jsonObject = JSONObject(response!!.body())
                        val data = jsonObject.getJSONObject("data")
                        val jsonArray = data.getJSONArray("list")

                        this@StudyCollectionActivity.data.clear()
                        for (i in 0 until jsonArray.length()) {
                            val collectionEntity = CollectionEntity()
                            val knowledgeType = jsonArray.getJSONObject(i).getInt("knowledgeType")
                            val knowledgeTitle = jsonArray.getJSONObject(i).getString("knowledgeTitle")
                            val knowledgeContent = jsonArray.getJSONObject(i).getString("knowledgeDescribe")
                            val coverImg = jsonArray.getJSONObject(i).getString("coverImg")
                            val fileAddress = jsonArray.getJSONObject(i).getString("fileAddress")
                            val knowledgeId = jsonArray.getJSONObject(i).getInt("knowledgeId")
                            val createDate = jsonArray.getJSONObject(i).getLong("createDate")
                            val id = jsonArray.getJSONObject(i).getInt("id")


                            collectionEntity.knowledgeType = knowledgeType
                            collectionEntity.knowledgeTitle = knowledgeTitle
                            collectionEntity.knowledgeContent = knowledgeContent
                            collectionEntity.knowledgeId = knowledgeId
                            collectionEntity.id = id
                            collectionEntity.coverImg = coverImg
                            collectionEntity.fileAddress = fileAddress
                            collectionEntity.createDate = createDate

                            this@StudyCollectionActivity.data.add(collectionEntity)
                        }

                        val sListIterator = this@StudyCollectionActivity.data.iterator()
                        while (sListIterator.hasNext()) {
                            val str = sListIterator.next()
                            if (str.knowledgeType == 0) {
                                sListIterator.remove()
                            }
                        }
                        studyCollectionAdapter.notifyDataSetChanged()
                    }
                })
    }

    override fun onDestroy() {
        super.onDestroy()
        RxBus.getDefault().unregister(this)
        mPlayerBarView = null
        unbindService(conn)
    }

    private fun setOnRecyclerViewScrollDirectListener(rvList: RecyclerView) {
        rvList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                if (dy > 0) {
                    //todo 隐藏播放布局
                    if (Math.abs(dy) > 2) {

                        if (mPlayerManager!!.getPlayerBarVisibilityState()) {
                            mPlayerBarView!!.setPlayerBarVisibility(false)
                        }

                    }

                } else {
                    //todo 显示播放布局
                    if (Math.abs(dy) > 2) {
                        if (mPlayerManager!!.getPlayerBarVisibilityState()) {
                            mPlayerBarView!!.setPlayerBarVisibility(true)
                        }

                    }
                }
            }
        })
    }
}
